import { messages} from "share/common";
import React from 'react'
import SlideFrame from 'components/slide-frame'
import { Button, Table, Modal, Form, Popconfirm, Row, Col, Icon, Badge, message, Alert, Popover, InputNumber, Radio } from 'antd';
import menuRoute from 'routes/menuRoute'
import 'styles/expense-reimbursement-control/mileage-subsidy/mileage-subsidy.scss'
import NewSubsidyRule from 'containers/expense-reimbursement-control/mileage-subsidy/new-subsidy-rule'
import StaircaseMileage from 'containers/expense-reimbursement-control/mileage-subsidy/staircase-mileage'
import mileageSubsidyService from 'containers/expense-reimbursement-control/mileage-subsidy/mileage-subsidy.service'
import errorMessage from "share/errorMessage";

class MileageSubsidy extends React.Component {
  constructor(props) {
  super(props);
  this.state = {
    tieredPageNo:0,
    tieredPageSize:10,
    unitPageNo:0,
    unitPageSize:10,
    loading:false,
    showStaircaseMileage:false,
    unitPriceRange: 0,
    editBeforeUnitPriceRange: 0,
    tieredPagination: {
        total: 0,
    },
    unitPagination: {
        total: 0,
    },
    mileageSetting:menuRoute.getRouteItem('staircase-mileage-setting','key'),
    priceMileageSetting:menuRoute.getRouteItem('price-mileage-setting','key'),
    tieredColumns: [
        {
            title: messages('setting.key767'/*序号*/), /*序号*/
            dataIndex: "index",
            width: 48,
            render: (value, record, index) => index + 1 + this.state.tieredPageNo * this.state.tieredPageSize
        },
        {
            title: messages('setting.key768'/*规则名称*/), /*规则名称*/
            key: "name",
            dataIndex: "name",
            render: value => <Popover content={value}>{value}</Popover>
        },
        {
            title: messages('setting.key769'/*适用人员*/),/*适用人员组*/
            key: "userGroupVOs",
            dataIndex: "userGroupVOs",
            render:this.tieredUserGroupFilter
        },
        {
            title: messages('setting.key770'/*币种*/),/*币种*/
            key: "currency",
            width: 48,
            dataIndex: "currency"
        },
        {
            title: messages('setting.key771'/*金额/公里*/),/*金额/公里*/
            key: "stepPrice",
            align: "right",
            dataIndex: "stepPrice",
            render: value => <Popover content={value}>{value}</Popover>
        },
        {
            title: messages('setting.key772'/*状态*/),/*状态*/
            key: "enabled",
            dataIndex: "enabled",
            render: (value, record) => (
                <Badge status={value ? 'success' : 'error'}
                       text={value ? messages('common.enabled') : messages('common.disabled')}/>
            )
        }
        ,
        {
            title: messages('setting.key773'/*操作*/),/*操作*/
            key: "operate",
            dataIndex: "operate",
            render: (text,record) => (
                <span>
                   <a onClick={(e) => this.handleTieredEdit(e, record)}>{messages('common.edit')}</a>
                  <span className="ant-divider"/>
                  <Popconfirm title={messages('common.confirm.delete')} onConfirm={(e) => this.deleteTieredRule(e, record)}>
                  <a>{messages( 'common.delete')}</a></Popconfirm>
                </span>
            )
        }
    ],
    unitColumns:[
      {
        title: messages('setting.key767'/*序号*/),/*序号*/
        dataIndex: "index",
        width: 48,
        render: (value, record, index) => index + 1 + this.state.unitPageNo * this.state.unitPageSize
      },
      {
        title: messages('setting.key769'/*适用人员*/),/*适用人员组*/
        key: "optionalUserGroup",
        dataIndex: "optionalUserGroup",
        render:this.unitUserGroupFilter
      },
      {
        title: messages('setting.key770'/*币种*/),/*币种*/
        key: "currency",
        width: 48,
        dataIndex: "currency"
      },
      {
        title: messages('setting.key771'/*金额/公里*/),/*金额/公里*/
        key: "unitPrice",
        dataIndex: "unitPrice",
        /*render: this.filterMoney,*/
        render: value => <Popover content={value}>{value}</Popover>,
        align: "right",
      },
      {
        title: messages('setting.key199'/*描述*/),/*描述*/
        key: "ruleDesc",
        dataIndex: "ruleDesc",
        width: "25%",
        render: value => <Popover content={value}>{value}</Popover>
      },
      {
        title: messages('setting.key772'/*状态*/),/*状态*/
        key: "enabled",
        dataIndex: "enabled",
        render: (value, record) => (
          <Badge status={value ? 'success' : 'error'}
                 text={value ? messages('common.enabled') : messages('common.disabled')}/>
        )
      }
      ,
      {
        title: messages('setting.key773'/*操作*/),/*操作*/
        key: "operate",
        dataIndex: "operate",
        render: (text,record) => (
          <span>
                  <a onClick={(e) => this.handleUnitEdit(e, record)}>{messages('common.edit')}</a>
                  <span className="ant-divider"/>
                  <Popconfirm title={messages('common.confirm.delete')} onConfirm={(e) => this.deleteUnitRule(e, record)}>
                  <a>{messages('common.delete')}</a></Popconfirm>
                </span>
        )
      }
    ],
    tieredData: {},
    unitData: [],
    valuation: 'unit-price-model',
    visible: false,
    showUnitSlideFrame: false,
    frameData: {
      key: 'unit-price-model',
      data: [],
      stepOID: null,
      isNew: true,
      record: null,
      ladderModifyStatus: null
    },
    stepOID: '',
    slideFrameParams: 'unit-price-model',
    mileageData: [],
    ladderModifyStatus: '',
    warning: true,//是否显示顶部的warning
    subApplicationPage: menuRoute.getRouteItem('sub-application', 'key'),    //子应用管理的页面项
    productInvoiceType: {
      name: messages('expense-reimbursement-control.key113')/*每月里程可生成费用次数*/,
      mode: [
        { key: '1', title: messages('expense-reimbursement-control.key114')/*一次*/ },
        { key: '2', title: messages('expense-reimbursement-control.key115')/*多次*/ }
        ]
    },
    modify: {
      name: messages('expense-reimbursement-control.key141')/*里程补贴费用中是否允许修改出发到达途径的时间/地点信息*/,
      mode: [
        { value: true, title: messages('expense-reimbursement-control.key142')/*允许*/ },
        { value: false, title: messages('expense-reimbursement-control.key143')/*不允许*/ }
      ]
    },
    editable: false // 是否可以修改途经点等信息 配置
  }
}

  componentWillMount(){
    this.switchMode()
    this.getLadderModifyStatus()
    this.queryDeviateValue();
  }

  //查询精度值
  queryDeviateValue = () => {
    let { unitPriceRange, editBeforeUnitPriceRange, editable } = this.state;
    mileageSubsidyService.queryDeviateValue()
      .then(res => {
        if (res.data) {
          unitPriceRange = res.data.unitPriceRange;
          editBeforeUnitPriceRange = res.data.unitPriceRange;
          editable = !!res.data.editable;
          this.setState({ unitPriceRange, editBeforeUnitPriceRange, editable });
        }
      });
  };

  switchMode = ()=>{
    mileageSubsidyService.isLadder().then(res =>{
      if(res.data.mode === 9001){
        this.setUnitModel()
      }else{
        this.setTieredModel()
      }
    })
  }

  //获取是否修改规则状态
  getLadderModifyStatus = ()=>{
    mileageSubsidyService.getLadderModifyStatus().then(res =>{
      this.setState({ladderModifyStatus:res.data})
    })
  }

  //阶梯模式表格适用人员过滤
  tieredUserGroupFilter = (record)=>{
    if(!record) return <span>{messages('setting.key774'/*通用*/)}</span>
    let showArray=[];
    record.length > 0 && record.map(item => {
      showArray.push(item.groupName);
    })
    let showValue = showArray.join('、');
    return <Popover content={showValue}>{showValue}</Popover>;
  };

  //单价模式表格适用人员过滤
  unitUserGroupFilter = (record) => {
    if (!record) return <span>{messages('setting.key774'/*通用*/)}</span>
    let showArray = [];
    record.groups.length > 0 && record.groups.map(item => {
      showArray.push(item.name);
    })
    let showValue = showArray.join('、');
    return <Popover content={showValue}>{showValue}</Popover>;
  }

  //得到单价模式规则数据
  getUnitRuleList(){
    this.setState({ loading: true });
    const { unitPageNo,unitPageSize }  = this.state
    mileageSubsidyService.getUnitRuleList(unitPageNo,unitPageSize).then((response) =>{
      this.setState({
        loading:false,
        unitData:response.data,
        unitPagination: {
          total: Number(response.headers['x-total-count']) ? Number(response.headers['x-total-count']) : 0,
          current: unitPageNo + 1,
          onChange:this.unitChangePager
        }
      })
    })
  }

  //得到阶梯模式规则数据
  getTieredRuleList(){
    this.setState({ loading: true });
    let param = {
      pageNo:this.state.tieredPageNo,
      pageSize:this.state.tieredPageSize
    }
    mileageSubsidyService.getTieredRuleList(param).then((response) =>{
      this.setState({
        loading:false,
        tieredData:response.data,
        tieredPagination: {
          total: Number(response.headers['x-total-count']) ? Number(response.headers['x-total-count']) : 0,
          onChange: this.tieredChangePager,
          current: this.state.tieredPageNo + 1
        },
        mileageData:response.data.stepVOs,
        stepOID:response.data.stepOid,
        showStaircaseMileage:true
      })
    })
  }

  //删除单价模式规则
  deleteUnitRule = (e,record) =>{
    this.setState({loading: true});
    mileageSubsidyService.deleteUnitRuleList(record.ruleOID).then((response) =>{
      if (response.status === 200){
        this.setState({loading: false});
        message.success(messages("common.delete.success",{name:''}));
        this.getUnitRuleList();
      }
    }).catch(() => {
      this.setState({loading: false});
      message.error(messages( "common.operate.filed"));
    })
  };

  //删除阶梯模式规则
  deleteTieredRule = (e,record) =>{
    mileageSubsidyService.deleteTieredRuleList(record.ruleOID).then((response) =>{
      if (response.status === 200){
        this.setState({loading: false});
        message.success(messages("common.delete.success",{name:''}));
        this.getTieredRuleList();
      }
    }).catch(() => {
      this.setState({loading: false});
      message.error(messages( "common.operate.filed"));
    })
  }

  //单价模式点击分页
  unitChangePager = page=>{
    if(page-1 !== this.state.unitPageNo){
      this.setState({
        unitPageNo:page - 1,
        loading:true
      }, () =>{
        this.getUnitRuleList()
      })
    }
  }

  //阶梯模式点击分页
  tieredChangePager = page=>{
    if(page-1 !== this.state.tieredPageNo){
      this.setState({
        tieredPageNo:page - 1,
        loading:true
      }, () =>{
        this.getTieredRuleList()
      })
    }
  };

  setTieredModel(){
    this.setState({
      valuation:'tiered-price-model',
    },this.getTieredRuleList())
  }

  setUnitModel(){
    this.setState({
      valuation:'unit-price-model'
    },this.getUnitRuleList())
  }

  /**
   * switchToLadder
   * @param mode 9002代表切换到阶梯模式，9001是单价模式
   */
  switchToLadder = ()=>{
    let mode = this.state.valuation === 'unit-price-model' ? 9002 :9001
    mileageSubsidyService.setMode(mode).then(res =>{
      if(res.status === 200){
        //切换成功
        message.success(messages('setting.key775'/*切换成功*/));
        if(mode === 9002){
          this.context.router.push(this.state.mileageSetting.url);
          // this.setTieredModel();
        }else{
          this.setUnitModel();
        }
      }
    }).catch(e=>{
      // 切换失败
      message.error(messages('setting.key776'/*切换失败*/));
    })
  }

  showConfirm = (e)=>{
    e.stopPropagation()
    this.setState({visible: true})
    const title = this.state.valuation === 'unit-price-model' ? messages('setting.key777'/*切换到阶梯计价*/) : messages('setting.key778'/*切换到单价计价*/)
    Modal.confirm({
      title: title,
      okText: messages("common.ok"),
      cancelText: messages("common.cancel"),
      onOk:()=>{
        this.switchToLadder()
      },
      onCancel:()=>{

      }
    });
  };

  handleMileageSetting(){
    const {valuation} = this.state;
    // 阶梯模式
    if (valuation === 'tiered-price-model') {
      this.context.router.push(this.state.mileageSetting.url);
    } else if (valuation === 'unit-price-model') {
      // 单价模式
      this.context.router.push(this.state.priceMileageSetting.url);
    }
  }

  handleNewRule = ()=>{
    if(this.state.valuation === 'unit-price-model'){
      this.setState({
        frameData: {
          key: 'unit-price-model',
          data: [],
          isNew:true,
          record:null
        }},()=>{
        this.showSlide(true)
      })
    }else{
      this.setState({
        frameData:{
          key:'tiered-price-model',
          data:this.state.mileageData,
          stepOID:this.state.stepOID,
          isNew:true,
          record:null
        }},()=>{
        this.showSlide(true)
      })
    }
  };

  //单价规则编辑
  handleUnitEdit = (e,record) =>{
    this.setState({
      showUnitSlideFrame:true,
      frameData: {
        key: 'unit-price-model',
        data: [],
        isNew:false,
        record:record
      }
    },()=>{
      this.showSlide(true);
    })
  }

  //阶梯编辑
  handleTieredEdit = (e,record) =>{
    mileageSubsidyService.getTieredRuleDetail(record.ruleOID).then( response =>{
      this.setState(
        {
          frameData: {
            key: 'tiered-price-model',
            data: this.state.mileageData,
            ladderModifyStatus:this.state.ladderModifyStatus,
            isNew:false,
            record:response.data.stepRuleVO
          }
        },()=>{
          this.showSlide(true)
        })
    })
  };

  //关闭slideFrame刷新列表
  handleCloseSlide = (success) =>{
    success && this.state.valuation === 'unit-price-model' ? this.getUnitRuleList() : this.getTieredRuleList();
    this.getLadderModifyStatus();
    this.setState({ showUnitSlideFrame : false});
  };

  showSlide = (flag) =>{
    this.setState({showUnitSlideFrame:flag})
  };
  //编辑偏离税
  editDeviate = (enable) => {
    let {editBeforeUnitPriceRange,unitPriceRange}=this.state;
    if (enable) {
      this.setState({editBeforeUnitPriceRange: unitPriceRange})
    } else {
      this.setState({unitPriceRange: editBeforeUnitPriceRange})
    }
    this.setState({editDeviateStatus: enable})
  }
  //保存偏离税
  saveDeviate = ()=>{
    let {unitPriceRange}=this.state;
    mileageSubsidyService.saveDeviateValue(unitPriceRange).then(res=>{
      this.setState({loading: false});
      this.setState({editBeforeUnitPriceRange: unitPriceRange})
      this.setState({editDeviateStatus: false})
    }).catch(e=>{
      errorMessage(e.response);
      this.setState({loading:false})
    })
  };

  handleModeChange = (e) => {
    const { target: value } = e;
    const { tieredData, tieredData: { stepVOs } } = this.state;
    let stepMileages = stepVOs.map(item => item['startUnit']);
    stepMileages.push(-1);
    mileageSubsidyService.addStep({ manyInvoice: value.value, stepMileages })
      .then(() => {
        message.success(messages('common.operate.success')/*操作成功*/);
        tieredData.manyInvoice = value.value;
        this.setState({ tieredData });
      });
  };

  handleModifyChange = (e) => {
    const { target: value } = e;
    let { editable } = this.state;
    mileageSubsidyService.setEditable({ editable: value.value })
      .then(() => {
        editable = value.value;
        message.success(messages('common.operate.success')/*操作成功*/);
        this.setState({ editable });
      });
  };

  renderModeType = () => {
    const { tieredData: { manyInvoice = '1' }, productInvoiceType: { mode, name } } = this.state;
    return (
      <section className="mileage-subsidy--mode">
        <div>{name}：</div>
          <Radio.Group onChange={this.handleModeChange} value={manyInvoice}>
            {
              mode.map(item => <Radio value={item.key}>{item.title}</Radio>)
            }
          </Radio.Group>
      </section>
    );
  };

  renderEditLocation = () => {
    const { editable, modify: { mode, name } } = this.state;
    return (
      <section className="mileage-subsidy--mode">
        <div>{name}：</div>
        <Radio.Group onChange={this.handleModifyChange} value={editable}>
          {
            mode.map(item => <Radio value={item.value}>{item.title}</Radio>)
          }
        </Radio.Group>

      </section>
    );
  };

  render() {
    const { unitColumns,tieredColumns,showUnitSlideFrame,mileageData,valuation,frameData,loading,unitData,
      tieredData,unitPagination,tieredPagination,showStaircaseMileage,ladderModifyStatus, warning,editDeviateStatus,unitPriceRange } = this.state;
    const message = (
      <Row>
        <Col span={23}> {messages('setting.key1507')/*如需开启/禁用该功能，请前往【APP应用管理 - 里程补贴】页面*/}：
        </Col>
        <Col span={1} onClick={() => {this.setState({warning: false})}} style={{textAlign: 'right', cursor: 'pointer'}}>X</Col>
      </Row>
    );
    const description = (
      <div>
        <Row span={20} style={{marginBottom: 5}}>1、{messages('setting.key1508')/*将该应用状态设置为【启用 】，用户可在【APP-应用】界面 看到该应用。*/}</Row>
        <Row span={20} style={{marginBottom: 5}}>2、{messages('setting.key1509')/*将该应用状态设置为【禁用 】，该应用将不在【APP-应用】中显示。*/}</Row>
      </div>
    );
    return (
      <div className="mileage-subsidy">
        <div style={{marginBottom: 20}}>
          {
            warning ?
              <div style={{marginBottom: 20}}>
                <Alert
                  message={message}
                  description={description}
                  type="warning"
                  showIcon
                />
              </div>
              : null
          }
        </div>
          <div className='header'>
              <Row type='flex' align='middle'>
                  <Col span={8}>
                    {valuation === 'unit-price-model' ?  <span className="mode">{messages('setting.key779'/*当前模式：单价模式*/)}</span> : <span className="mode">{messages('setting.key780'/*当前模式：阶梯模式*/)}</span>}
                    {valuation !== 'unit-price-model' && <span className="edit"><Icon type="edit" className='icon-edit'/><a onClick={()=>{this.handleMileageSetting()}}>{messages("common.edit")}</a></span>}
                  </Col>
                  <Col span={9}/>
                  <Col span={7} className='switch-mode'>
                    <span>
                      {
                        messages(valuation === 'unit-price-model' ?
                          "setting.key777" :
                          "setting.key778")
                      }
                    </span>
                    <Button onClick={this.showConfirm}><Icon type="arrow-right"/></Button>
                  </Col>
              </Row>
            {/*员工是否可修改费用*/}
            {valuation === 'unit-price-model' && (
              <div style={{marginTop: '20px'}}>{messages('setting.key781'/*员工是否可修改单价*/)}:
                <span>{messages('setting.key1559')/*修改后的单价偏离*/}{editDeviateStatus ?
                  <span style={{margin: '0 5px'}}><InputNumber step={0.01} min={0} precision={2} style={{width: '8%'}} max={9999}
                                                               value={unitPriceRange} onChange={(value)=>{ this.setState({unitPriceRange:value}) }}/></span> : unitPriceRange}%{messages('setting.key1560')/*时,禁止生成费用。*/}{editDeviateStatus ?
                  <span style={{marginLeft: '30px'}}><Button size="small" onClick={this.saveDeviate} type="primary"
                                                             loading={loading}>{messages('setting.key1079')/*保存*/}</Button> &nbsp;&nbsp;
                    <Button size="small" onClick={() => this.editDeviate(false)}>{messages('setting.key1080')/*取消*/}</Button></span> :
                  <span className="edit"><Icon type="edit" className='icon-edit'/><a
                    onClick={() => this.editDeviate(true)}>{messages("common.edit")}</a></span>}</span>
              </div>
            )}
            {valuation === 'unit-price-model' ?
              // 人员组优先级＞通用，当1个人在多个人员组时，取生成费用金额最小的规则
              (
                <div style={{"marginTop": "15px"}}>
                  <span className="rules">{messages('setting.key784'/*人员组优先级＞通用，当1个人在多个人员组时，取生成费用金额最小的规则*/)}</span>
                </div>
              ) : <StaircaseMileage mileageData={mileageData} show={showStaircaseMileage}/>}
            {(ladderModifyStatus === 1 && valuation === 'tiered-price-model' && tieredData.stepRuleVOs && tieredData.stepRuleVOs.length>0) ?
              <Alert description={messages('setting.key785'/*里程阶梯已刷新，请补全各规则中的相应金额，以免影响使用*/) /*里程阶梯已刷新，请补全各规则中的相应金额，以免影响使用*/}
                     type="warning"
                     banner /> : ''}
            {valuation === 'tiered-price-model' ? this.renderModeType() : this.renderEditLocation()}
          </div>
          <Button type="primary" className="new-button" onClick={this.handleNewRule}>{messages('setting.key786'/*新建规则*/)}</Button>
          <div className="rule-table">
            {valuation === 'unit-price-model' ?
              <Table dataSource={unitData}
                     size="middle"
                     bordered
                     columns={unitColumns}
                     loading={loading}
                     pagination={unitPagination}
                     rowkey="ruleOID"
              />
              :
              <Table dataSource={tieredData.stepRuleVOs}
                     size="middle"
                     bordered
                     columns={tieredColumns}
                     loading={loading}
                     pagination={tieredPagination}
                     rowkey="ruleOID"
              />
            }
          </div>
          <SlideFrame title={frameData.isNew ? messages('setting.key786'/*新建规则*/) : messages('setting.key787'/*编辑规则*/)}
                      show={showUnitSlideFrame}
                      content={NewSubsidyRule}
                      onClose={() => this.showSlide(false)}
                      params={frameData}
                      afterClose={this.handleCloseSlide}
          />
      </div>
    )
  }
}
MileageSubsidy.contextTypes = {
    router: React.PropTypes.object
};

const wrappedMileageSubsidy = Form.create()(MileageSubsidy);

export default wrappedMileageSubsidy;
